package com.jt.interceptor;

import java.util.ArrayList;
import java.util.List;

/**拦截器*/
interface Interceptor{
    boolean doPre();
    void doPost();
}
/**处理器*/
interface Handler{
    void doHandle();
}
/**
 * 执行链设计(所有项目中的执行(Execution)链(Chain)都是预先设计好的)
 */
class ExecutionChain{
    //拦截器是边缘业务
    private List<Interceptor> interceptors;
    //处理器是核心业务
    private Handler handler;
    public ExecutionChain(List<Interceptor> interceptors, Handler handler) {
        this.interceptors = interceptors;
        this.handler = handler;
    }

    //执行业务逻辑
    public void execute(){//proceed()
        //1.执行拦截器(Interceptor)中的doPre方法
        for(int i=0;i<interceptors.size();i++)
             interceptors.get(i).doPre();
        //2.执行处理器(Handler)中的doHandle方法
        handler.doHandle();
        //3.执行拦截器(Interceptor)中的doPost方法
        for(int i=interceptors.size()-1;i>=0;i--)
            interceptors.get(i).doPost();
    }

}
public class ExecutionChainTests {
    public static void main(String[] args) {
        List<Interceptor> interceptors=new ArrayList<>();
        interceptors.add(new Interceptor() {
            @Override
            public boolean doPre() {
                System.out.println("doPre1");
                return false;
            }

            @Override
            public void doPost() {
                System.out.println("doPost1");
            }
        });
        interceptors.add(new Interceptor() {
            @Override
            public boolean doPre() {
                System.out.println("doPre2");
                return false;
            }

            @Override
            public void doPost() {
                System.out.println("doPost2");
            }
        });
        Handler handler=()-> {
            System.out.println("执行任务...");
        };
        ExecutionChain chain=new ExecutionChain(interceptors,handler);
        chain.execute();
    }

}
